<template>
	<view style="background-color: #FFFFFF;">
		<view class="user box">
			<view class="" style="text-align: center;">我的</view>
			<image class="head" :src="avatarUrl"></image>
			<view class="cfff ftc ft16 mt30 pb15">
		    <view style="width: 200rpx;margin: auto;" v-if="isPhone || isCanUse">
				 <button v-if="isPhone" type='primary'
					style="line-height:1.5;background-color: rgba(255,255,255,0.0);
					border: 4rpx solid #7BDBD4;border-radius: 50rpx;font-size: 30rpx;
					padding-top: 10rpx;padding-bottom: 10rpx;"  
				 	open-type="getPhoneNumber"  @getphonenumber="getPhoneNumber">
				 	登录
				 </button>
				 <button v-else type='primary'
				 					style="line-height:1.5;background-color: rgba(255,255,255,0.0);
				 					border: 4rpx solid #7BDBD4;border-radius: 50rpx;font-size: 30rpx;
				 					padding-top: 10rpx;padding-bottom: 10rpx;"  
				 	 @click="wxGetUserInfo">
				 	获取昵称
				 </button>
			</view>
			
			<button v-if="isCanUse==false" class='wxUserInfo' type='primary' style="line-height:1.5;background-color: rgba(255,255,255,0.0);">
				{{nickName}}
			</button>
			</view>
		</view>
		<view class="list pl25 pr25 box c000">
			<!-- <view class="pl20 pr20 bb box flex flex-ac" v-if="isPhone">
				<view class="it1 flex flex-ac">
					<text>登录手机号,获取更全面的诊疗服务</text>
					<button class='login_btn' style="line-height: 1.5;padding-left: 1;background-color: #F73809;font-size: 39rpx;margin-right: 1rpx;" type='primary' open-type="getPhoneNumber"  @getphonenumber="getPhoneNumber">
					  登录
					</button>
				</view>
			</view> -->
			<view class="pl20 pr20 bb box flex flex-ac" @click="advisoryNavigateTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/wdwz.png"></image>
					<text>我的问诊</text>
					<view class="red-dot" v-if="orderNum > 0"></view>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
			<view class="pl20 pr20 bb box flex flex-ac" @click="recordNavigateTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/dangan.png"></image>
					<text>档案病历管理</text>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
			<view class="pl20 pr20 bb box flex flex-ac" @click="tochufanglist()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/chufang.png"></image>
					<text>我的处方</text>
					<view class="red-dot" v-if="recipeNum > 0"></view>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
			<view class="pl20 pr20 bb box flex flex-ac" @click="mydoctorlistTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/wdys.png"></image>
					<text>我的医生</text>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
			<view class="pl20 pr20 bb box flex flex-ac" @click="suifanglistTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/suif.png"></image>
					<text>我的随访表</text>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
			<view class="pl20 pr20 bb box flex flex-ac"  @click="addressNavigateTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/wddz.png"></image>
					<text>我的地址</text>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>

			<view class="pl20 pr20 bb box flex flex-ac" @click="opinionNavigateTo()">
				<view class="it1 flex flex-ac">
					<image class="typeimg" src="../../static/images/kef.png"></image>
					<text>意见反馈</text>
				</view>
				<view class="flex flex-ac">
					<image class="arrow" src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png"></image>
				</view>
			</view>
		</view>
		<view class="ftc mt30 mb30">
			<view class="pt30 pb30">
				<!-- <view class="c999 ft10">版本：1.0.1 </view> -->
				<!-- <view class="c999 ft10 mt10">使用《xx》即代表完全接受我们的  <text class="c083fdc ml15" @click="toAgreement">用户协议</text> </view> -->
			</view>
		</view>
		<uni-popup ref="popup" type="message">
		    <uni-popup-message :type="warnType" :message=warnMessage :duration="warnTime"></uni-popup-message>
		</uni-popup>
		<CustomTabBar  current="/pages/user/index" />
	</view>
</template>

<script>

const WxAuth =  require('@/utils/wxlogin');
	import CustomTabBar  from '@/components/CustomTabBar/index.vue';
	export default {
		components: { CustomTabBar } 
		,
		data() {
			return {
				getUserHead:false,
				isPhone:false,
				code:"",
				session_key: '',//获取手机号需要的数据
				encryptedData:"",//获取手机号需要的数据
				iv:"",//获取手机号需要的数据
				collectForDoctor:0,//关注医生数量
				medRecipeCount:0,//用户的处方数量
				freeCount:0,//咨询数量
				orderNum: 0,// 未支付问诊数量
				recipeNum: 0,// 未支付处方数量
				warnMessage:'错误',//消息内容
				warnType:'warn',//消息类型  success/warn/info/error
				warnTime:1000,//消息提醒延长时间
				usrUserId:null,
				isCanUse: true,//默认为true  记录当前用户是否是第一次授权使用的
				avatarUrl:'../../static/images/mrtx.png',//微信头像
				wx: "https://app.mzmzb.com", //https://app.mzmzb.com   http://localhost:6110
				nickName:'获取微信昵称',//微信昵称
			};
		},
		onLoad() {
			WxAuth.onLogin();
		},
		onShow() {
			let storage_nickName = uni.getStorageSync("nickName");
			if(storage_nickName&&storage_nickName.length>0){
				this.nickName = uni.getStorageSync("nickName");//昵称
				this.avatarUrl = uni.getStorageSync("avatarUrl"); //头像
				this.isCanUse=false;
			}
			if(!this.isCanUse){
				this.wxGetUserInfo();
			}
			var usrUserId = uni.getStorageSync("usrUserId");
			if(usrUserId){
				this.isPhone = false;
				this.usrUserId=usrUserId;
				//初始化数据关注医生数量
				this.initCollectForDoctor();
				//初始化数据处方数量
				this.initMedRecipe();
				//初始化数据咨询数量
				this.initFreeSum();
				// 初始化未支付和处方数量
				this.initNopay()
			}else{
				this.isPhone = true;
			}
			var userId = uni.getStorageSync("usrUserId");
			// if(userId){
			// 	this.loginHX(userId)
			// }
			let isCanUse = uni.getStorageSync("isCanUse");
			if(isCanUse&&isCanUse=='1'){
				this.nickName = uni.getStorageSync("nickName"); //昵称
				this.avatarUrl = uni.getStorageSync("avatarUrl"); //头像
				this.isCanUse=false;//记录是否第一次授权 false:表示不是第一次授权
			}
		},
		methods: {
			tochufanglist(){
				uni.navigateTo({
					url: '/pages/myrecipe/index?recipeNum='+this.recipeNum
				});
			},
			wxGetUserInfo(){ //第一授权获取用户信息===》按钮触发
				let _this = this;
				// 获取用户信息
				uni.getUserProfile({
					desc: 'weixin',
					success: function (infoRes) {
						_this.nickName = infoRes.userInfo.nickName; //昵称
						_this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
						_this.isCanUse=false;//记录是否第一次授权 false:表示不是第一次授权
						uni.setStorageSync('isCanUse', '1');
						uni.setStorageSync('nickName', infoRes.userInfo.nickName);
						uni.setStorageSync('avatarUrl', infoRes.userInfo.avatarUrl);
					},fail:function (fail){
						
					}
				});
			},
			// getUserInfo(){
			// 	uni.getUserProfile({
			// 		desc:'weixin',
			// 		success:res=>{
			// 			console.log(res.rawData)
			// 		}
			// 	})
			// },
			//登录
			getPhoneNumber(e){
				var that = this;
				if(e.detail.errMsg =="getPhoneNumber:ok"){
					that.encryptedData = e.detail.encryptedData;
					that.iv = e.detail.iv;
					that.getCode(e.detail.encryptedData,e.detail.iv,this.hspId);
				}
			},
			//获取用户id并存入缓存
			getCode(encryptedData,iv,hspId){
				var that = this;
				 WxAuth.checkSession().then(code => {
					 WxAuth.getUserIdByPhone(code,encryptedData,iv,hspId).then(res =>{
							if(res.success){
								that.warnMessage = '登录成功';
								that.warnType = 'success';
								that.$refs.popup.open();
								// let hx=res.result
								that.isPhone = false;
								that.usrUserId = res.result;
								uni.request({
									url:'https://app.mzmzb.com/application-usrapp/login/wxGetToken.tz?usrUserId='+that.usrUserId,
									method:'POST',
									success:(res)=> {
										uni.setStorageSync('lgToken',res.data.result)
									}
								})
								uni.login({
									provider: 'weixin',
									success: (loginres) =>{
										console.log(1111,loginres)
										if (loginres.errMsg == "login:ok") {
											that.getOpenIdByHspId(loginres.code)
											// that.loginHX(hx)
											// that.getSubscribe = true
											wx.getSetting({
											   withSubscriptions: true,
												success(res) {
													 var itemSettings = res.subscriptionsSetting.itemSettings
													 if (itemSettings) {
													   if (itemSettings['V42ulhq9LbAkFKriGtmnZitBWUggp6XkoCdr-OBwkco'] === 'accept'
															&& itemSettings['yWT8S-QFCJGdRDVcYwoSh9YlCr_77nbqLp0aUtIEITs'] === 'accept') {
															that.getSubscribe = false
													   }else{
															that.getSubscribe = true
													   }
													 }else{
														 that.getSubscribe = true
													 }
												},
												fail(res) {
													that.getSubscribe = true
												}
											 })
										}
									}
								});
								;//登录环信
								//初始化数据关注医生数量
								that.initCollectForDoctor();
								//初始化数据处方数量
								that.initMedRecipe();
								//初始化数据咨询数量
								that.initFreeSum();
								// 初始化未支付和处方数量
								this.initNopay()
								that.getUserHead = true
							}else{
								that.warnMessage = res.errMsg;
								that.warnTime = 2000;
								that.$refs.popup.open();
							}
							
						})
				 });
			},
			getOpenIdByHspId(code){
				console.log(222)
				uni.request({
					url: this.wx + '/application-usrapp/wx/getOpenIdByHspId.tz',
					method: 'get',
					data: {
						code: code,
						userId: this.usrUserId,
						hspId: this.hspId
					},
					success: (res) => {
						console.log(res)
						this.passopenid=res.data.errMsg
						uni.setStorageSync('openId',res.data.errMsg)
						this.loginHX(this.usrUserId);//登录环信
					}
				})
			},
			//登录环信
		gethx(userId){
				if(uni.getStorageSync('openId')){
					this.passopenid=uni.getStorageSync('openId')
				}
				setTimeout(()=>{
					this.func.$request('login/hxLogin.tz?usrUserId=' + userId,{},'POST').then(item=>{
						var test_account = userId + '';
						uni.setStorageSync("test_psword", item.data.errMsg)
						this.$conn.open({
							apiUrl: this.$im.config.apiURL,
							user: test_account,
							pwd: item.data.errMsg,
							grant_type: "password",
							appKey: this.$im.config.appkey
						});
					})
				},2000)	
			},
		loginHX(userId){
			var test_account = userId+'';
			let test_psword=''
			if(uni.getStorageSync("test_psword")){
				test_psword = uni.getStorageSync("test_psword")
				uni.setStorageSync("usrUserId",test_account)
				uni.setStorageSync("myUsername",test_account);
				this.$conn.open({
					apiUrl: this.$im.config.apiURL,
					user: test_account,
					pwd: test_psword,
					grant_type: "password",
					appKey: this.$im.config.appkey
				});
			}else{
				test_psword = uni.getStorageSync("test_psword")
				uni.setStorageSync("usrUserId",test_account)
				uni.setStorageSync("myUsername",test_account);
				this.gethx(userId)
				
			}	
		},
			initCollectForDoctor() {
				var that = this;
				var usrUserId = that.usrUserId; //用户id
				var hosId = this.hspId; //永川医院id
				that.func.$request('userCollect/getDoctorCount.tz', {
					usrUserId: usrUserId,
					hosId: hosId
				}, 'GET').then(res => {
					if (res.data.success) {
						that.collectForDoctor = res.data.result;
					}
				})
			},
			initMedRecipe() {
				var that = this;
				var usrUserId = that.usrUserId; //用户id
				var hosId = this.hspId; //永川医院id
				that.func.$request('recipe/userMedRecipeCount.tz', {
					usrUserId: usrUserId,
					hosId: hosId
				}, 'GET').then(res => {
					if (res.data.success) {
						that.medRecipeCount = res.data.result;
					}
				})
			},
			initFreeSum() {
				var that = this;
				var usrUserId = that.usrUserId; //用户id
				var hosId = this.hspId; //永川医院id
				that.func.$request('userOrd/getFree_dlCount.tz', {
					usrUserId: usrUserId,
					hosId: hosId
				}, 'GET').then(res => {
					if (res.data.success) {
						that.freeCount = res.data.result;
					}
				})
			},
			initNopay(){
				var that = this;
				var usrUserId = that.usrUserId;//用户id
				var hosId = this.hspId;//永川医院id
				that.func.$request('recipe/userNopayCount.tz',{usrUserId : usrUserId, hosId : hosId, isPay: 0},'GET').then(res=>{
					if(res.data.success){
						let { orderNum, recipeNum} = res.data.result
						that.orderNum = orderNum;
						that.recipeNum = recipeNum;
						var count = orderNum+recipeNum;
						if(count>0){
							uni.setTabBarBadge({
								index: 2,
								text: count.toString()
							})
						}else{
							uni.removeTabBarBadge({
									index: 2
							})
						}
					}
				})
			},
			//处方跳转
			myrecipeNavigateTo(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
					uni.navigateTo({
						url: '/pages/myrecipe/index?userId='+this.usrUserId
					});
				}else{
					that.warnMessage = "请先登录查看更多信息";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
			},
			//咨询跳转
			advisoryNavigateTo(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
					// that.loginHX(usrUserId);
					uni.navigateTo({
					    url: '/pages5/advisory/index?userId='+this.usrUserId+'&orderNum='+this.orderNum
					});
				}else{
					that.warnMessage = "请先登录查看更多信息";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
			},
			//档案信息跳转
			recordNavigateTo(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
				uni.navigateTo({
				    url: '/pages/record/index?userId='+this.usrUserId
				});
				}else{
					that.warnMessage = "请先登录查看更多信息";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
			
			},
			mydoctorlistTo(){
				uni.navigateTo({
				    url: '/pages4/mydoctorlist/index?userId='+this.usrUserId
				});
			},
			suifanglistTo(){
				uni.navigateTo({
				    url: '/pages3/suifang/index?userId='+this.usrUserId
				});
			},
			//消息通知跳转
			messNavigateTo(){
				uni.reLaunch({
				    url: '/pages/mess/index?userId='+this.usrUserId
				});
			},
			//我的收货地址
			addressNavigateTo(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
				uni.navigateTo({
				     url: '/pages/address/index?userId='+this.usrUserId
				});
				}else{
					that.warnMessage = "请先登录再查看地址";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
			},
			//意见反馈地址
			opinionNavigateTo(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
					uni.navigateTo({
						url: '/pages/opinion/index?userId='+this.usrUserId
					});
				}else{
					that.warnMessage = "请先登录查看更多信息";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
			},
			//电话客服
			makePhone(){
				uni.makePhoneCall({
				    phoneNumber: '114' //仅为示例
				});
			},
			//关于我们跳转
			aboutNavigateTo(){
				uni.navigateTo({
				    url: '/pages/about/index'
				});
			},
			//修改个人信息
			updateUserMess(){
				var that = this;
				var usrUserId = uni.getStorageSync("usrUserId");
				if(usrUserId){
					uni.navigateTo({
						url: '/pages/usermess/index?userId='+usrUserId
					});
				}else{
					that.warnMessage = "请先登录查看更多信息";
					that.warnTime  = 3000;
					that.$refs.popup.open();
				}
				
			},
			toquesIndex(){
				uni.navigateTo({
				    url: '/pages/ques/index'
				});
			},
			toAgreement(){
				uni.navigateTo({
				    url: '/pages/agreement/index'
				});
			}
		}
	};
</script>

<style lang="less">
	button::after{
		border:none;
	}
	.contact-btn {
	  display: inline-block;
	  position: absolute;
	  width: 100%;
	  background: salmon;
	    opacity: 0;
	}
	.ft10{
		font-size: 20rpx;
	}
	.c083fdc{
		color: #083fdc;
	}
	.user{
		width: 100%;
		// height: 380rpx;
		// background: #74a6fd;
		border-radius: 0 0 15rpx 5rpx;
		box-shadow: 10rpx 10rpx 10rpx 0 rgba(173,173,173,0.37);
		padding-top: 75rpx;
		.set{
			width: 42rpx;
			height: 42rpx;
			position: absolute;
			top: 35rpx;
			right: 30rpx;
			z-index: 10;
		}
		.head{
			width: 145rpx;
			height: 145rpx;
			border-radius: 50%;
			margin: 0 auto;
			margin-top: 50rpx;
			display: block;
		}
		.type{
			padding:50rpx;
		}
	}
	.list{
		min-height: 50vh;
		>view{
			height: 110rpx;
		}
		.typeimg{
			margin-right:20rpx;
			width: 48rpx;
			height: 48rpx;
		}
	}
	.user{
		background-size: 100% auto;
		background-repeat: no-repeat;
		height: 35vh;
		background-image: url('https://mzmzb.oss-cn-chengdu.aliyuncs.com/userBg.png');
		// background-color: rgba(170, 133, 98, 1);
	}
	
	.red-dot {
		width: 15rpx;
		height: 15rpx;
		border-radius: 50%;
		background-color: red;
		margin-left: 5rpx;
		margin-top: -10rpx;
	}
</style>
